package servlets;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import custom.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		RequestDispatcher dispatch;
		if(userName == null || password == null){
			dispatch = request.getRequestDispatcher("login.jsp");
		}else if(userName.length()*password.length() >0 && User.checkUser(userName, password)){
			try {
				request.getSession().setAttribute("user",new User(userName));
			} catch (SQLException e) {
				e.printStackTrace();
			}
			dispatch = request.getRequestDispatcher("home.jsp");
		}else{
			request.getSession().setAttribute("Note", "You entered incorrect Username op Password. <p></p> Please try again");
			dispatch = request.getRequestDispatcher("login.jsp");
		}
		dispatch.forward(request, response);
	}
}